package com.kuang.utils.template;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringFormateUtil {

    public static String processTemplate(String template, Map<String, Object> params){
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value==null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    public static String processTemplate(String template, Object...params){
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
        int index = 0;
        while (m.find()) {
            String param = m.group();
            String cindex = param.substring(2, param.length() - 1);
            Object value = params[Integer.parseInt(cindex)];
            m.appendReplacement(sb, value==null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args){
        Long id = 6748867555292897280L;
        System.out.println(processTemplate("商家会员还剩下${0}天，你的名字是${1}，${2}",id.toString(),"小明","234"));
    }
}
